package com.hison.tandainbao.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hison.tandainbao.entiy.pojo.domain.TbBlogComments;
import com.hison.tandainbao.entiy.pojo.dto.Comments;
import com.hison.tandainbao.response.ResponseResult;
import com.hison.tandainbao.service.TbBlogCommentsService;
import com.hison.tandainbao.mapper.TbBlogCommentsMapper;
import com.hison.tandainbao.util.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**
* @author hison
* @description 针对表【tb_blog_comments】的数据库操作Service实现
* @createDate 2024-03-31 22:04:29
*/
@Service
public class TbBlogCommentsServiceImpl extends ServiceImpl<TbBlogCommentsMapper, TbBlogComments>
    implements TbBlogCommentsService{

    @Autowired
    private  TbBlogCommentsMapper mapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public ResponseResult getComments(String blogID) {
        //1. 查询父评论
      TbBlogComments tbBlogComments =   mapper.getComment(blogID);


        return null;
    }

    @Override
    public ResponseResult deleteComment(String commentId) {
        boolean b = removeById(commentId);
        if (!b){
            return ResponseResult.error("删除失败");
        }
        return ResponseResult.ok("删除成功");
    }

    @Override
    public ResponseResult likeComment(String commentId) {
        //1. 获取登录用户
        Long userId = UserHolder.getUser().getId();
        //2.判断当前登录用户是否已经点赞
        String key = "comment:liked" + commentId;
        //判断zset中是否存在当前用户，没有则返回空   分数存在说明已经点赞了
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        if (score == null) {
            //3.如果未点赞，可以点赞
            //3.1数据库点赞数 +1
            boolean isSuccess = update().setSql("liked = liked + 1").eq("id", commentId).update();
            //3.2保存用户到redis集合   Zadd  key  value   score
            if (isSuccess) {
                stringRedisTemplate.opsForZSet().add(key, userId.toString(), System.currentTimeMillis());
            }
        } else {
            //4.如果已点赞  取消点赞
            //4.1 数据库点赞数 -1
            boolean isSuccess = update().setSql("liked = liked - 1").eq("id", commentId).update();
            //4.2 把用户从redis的set集合中移除
            if (isSuccess) {
                stringRedisTemplate.opsForZSet().remove(key, userId.toString());
            }
        }
        return ResponseResult.ok();
    }
}




